import java.util.Arrays;

public class Main {

    // 选择排序
    public static void selectSort(int[] array){
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            swap(array,i,minIndex);
        }
    }

    private static void swap(int[] array,int i,int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void selectSort2(int[] array) {
        int left = 0;
        int right = array.length - 1;
        while(left < right) {
            int minIndex = left;
            int maxIndex = left;
            for (int i = left + 1; i <= right; i++) {
                if (array[i] < array[minIndex]) {
                    minIndex = i;
                }
                if (array[i] > array[maxIndex]) {
                    maxIndex = i;
                }
            }
            swap(array,left,minIndex);
            if (maxIndex == left) {
                maxIndex = minIndex;
            }
            swap(array,right,maxIndex);
            left++;
            right--;
        }
    }

    // 堆排序
    public static void heapSort(int[] array){
        creatHeap(array);
        int end = array.length - 1;
        while(end > 0) {
            swap(array,0,end);
            siftDown(array,0,end);
            end--;
        }
    }
    //创建堆
    private static void creatHeap(int[] array) {
        for (int parent = (array.length - 1 - 1) / 2; parent >= 0; parent--) {
            //向下调整
            siftDown(array,parent,array.length);
        }
    }
    //向下调整
    private static void siftDown(int[] array, int parent, int len) {
        int child = 2 * parent + 1;
        while(child < len) {
            if (child + 1 < len && array[child] < array[child + 1]) {
                child++;
            }
            //找到左右子树的最大值
            if (array[child] > array[parent]) {
                swap(array,child,parent);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {1,2,6,7,9,5,3,8,4};
        //selectSort2(array);
        heapSort(array);
        System.out.println(Arrays.toString(array));
    }

}